package com.learnjava.learnjava1.service;

import com.learnjava.learnjava1.dto.CompanyDTO;
import com.learnjava.learnjava1.jpa.entity.CompanyEntity;
import com.learnjava.learnjava1.jpa.repository.CompanyRepository;
import com.learnjava.learnjava1.jpa.specification.CompanySpecification;
import com.learnjava.learnjava1.map.CompanyMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CompanyService {
    @Autowired
    CompanyRepository companyRepository;
    @Autowired
    CompanyMapper companyMapper;

    public CompanyDTO create(CompanyDTO companyDto) {
        return companyMapper.toDto(companyRepository.save(companyMapper.toEntity(companyDto)));
    }

    public CompanyDTO getCompanyById(Long id) {
        return companyRepository.findById(id)
                .map(companyMapper::toDto)
                .orElse(new CompanyDTO());
    }

    public Page<CompanyDTO> readAll(Pageable pageable) {
        Page<CompanyEntity> companyEntityPage = companyRepository.findAll(pageable);
        List<CompanyDTO> companyDTOList = companyMapper.toCompaniesDTOList(companyEntityPage.getContent());
        return new PageImpl<>(companyDTOList, pageable, companyEntityPage.getTotalElements());
    }

    public Page<CompanyDTO> filterAll(String title, Boolean active,Long id, Pageable pageable) {
        Page<CompanyEntity> companyEntityFilterPage = companyRepository.findAll(CompanySpecification.parseFilters(title, active,id), pageable);
        List<CompanyDTO> companyDTOList = companyMapper.toCompaniesDTOList(companyEntityFilterPage.getContent());
        return new PageImpl<>(companyDTOList, pageable, companyEntityFilterPage.getTotalElements());

    }

    public CompanyDTO update(CompanyDTO companyDto, Long id) {
        CompanyEntity companyEntity = companyRepository.findById(id).orElseThrow(() -> {
            throw new RuntimeException("Category not found -" + id);
        });
        companyMapper.update(companyDto, companyEntity);
        companyRepository.save(companyEntity);

        return companyMapper.toDto(companyEntity);
    }

    public void delete(Long id) {
        companyRepository.deleteById(id);
    }

    public CompanyEntity readById(Long id) {
        return companyRepository.findById(id).orElseThrow(() -> new RuntimeException("Category not found - " + id));
    }

}
